﻿using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using NativeWifi;

namespace Domain_Home
{
	public class LocationMonitor
	{
		private readonly String _home;
		private String _lastssid = String.Empty;
		public bool Athome { get; private set; }
		public event EventHandler<String> SsidChanged = (x, y) => {}; 
		private readonly NetworkAddressChangedEventHandler _handleChange;
		private readonly WlanClient _wlan = new WlanClient();

		public LocationMonitor(string home)
		{
			_home = home;
			_handleChange = (sender, args) =>
			{
				var ssid = GetSsid();
				if (!_lastssid.Equals(ssid))
				{
					_lastssid = ssid;
					Athome = ssid.Equals(_home);
					SsidChanged(this, ssid);
				}
			};
			Athome = GetSsid().Equals(_home);
		}

		public String GetSsid()
		{
			try
			{
				var s = _wlan.Interfaces.First(x => x.NetworkInterface.OperationalStatus.Equals(OperationalStatus.Up)).CurrentConnection.wlanAssociationAttributes.dot11Ssid;
				return new String(Encoding.ASCII.GetChars(s.SSID, 0, (int)s.SSIDLength));
			}
			catch (Exception)
			{
				return String.Empty;
			}
			
		}

		public void Attach()
		{
			NetworkChange.NetworkAddressChanged += _handleChange;
		}

		public void Detach()
		{
			NetworkChange.NetworkAddressChanged -= _handleChange;
		}
	}
}
